package com.gridmobi.xrtb.routers;


import com.google.common.collect.Maps;
import com.gridmobi.xrtb.component.lucene.BidIndex;
import com.gridmobi.xrtb.component.lucene.SimpleBidData;
import com.gridmobi.xrtb.handler.DeviceIdHandler;
import com.gridmobi.xrtb.handler.InfoHandler;
import com.gridmobi.xrtb.handler.impl.BidHandler;
import com.gridmobi.xrtb.handler.monitor.RtbStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("dsprtb")
public class Info {
    public final static String STATUS = "status";
    public final static String CAMPAIGNS = "campaigns";
    public final static String CFGS = "cfgs";
    public final static String SCHS = "schedule";
    public final static String BANNERS = "creatives";
    public final static String NATIVE = "natives";
    public final static String GEO_OS_APPS = "geoosapps";


    public final static String STATISTICS_ALL = "all_docs";
    public final static String STATISTICS_ACTIVE = "active_docs";
    public final static String STATISTICS_RAM = "ram_docs";
    public final static String STATISTICS_SEGMENTS = "segments";

    @Autowired
    private InfoHandler infoHandler;


    @GetMapping("ping")
    public Object ping() {
        return "OK";
    }

    @GetMapping("devq")
    public Object devq() {
        return DeviceIdHandler.GEO_OS_QUE;
    }

    @GetMapping("geofile")
    public Object geofile() {
        return DeviceIdHandler.GEO_FILES;
    }
    @GetMapping("devqsize")
    public Object devqsize() {
        Map<String, Integer> map = Maps.newHashMap();
        DeviceIdHandler.GEO_OS_QUE.forEach((k, v) -> {

            map.put(k, v.size());
        });
        return map;
    }


    @GetMapping("takedevid/{geo}/{os}")
    public Object takedevid(@PathVariable String geo, @PathVariable String os) {

        return DeviceIdHandler.takeDevid(geo, os);
    }


    @GetMapping("geof")
    public Object geof() {
        return DeviceIdHandler.GEO_FILES;
    }


    @GetMapping("")
    public Object info() {
        return infoHandler.info();
    }

    @GetMapping(GEO_OS_APPS)
    public Object geoosapps() {
        return SimpleBidData.GEO_OS_APPS;
    }

    @GetMapping(STATUS)
    public Object status() {
        return infoHandler.info();
    }

    @GetMapping(CAMPAIGNS)
    public Object campaigns() {
        return infoHandler.getDocs(BidIndex.CAMPAIGNS_W, 500, null);
    }


    @GetMapping(SCHS)
    public Object schs(@RequestParam(defaultValue = "") String cid) {
        return infoHandler.getDocs(BidIndex.CAMPAIGNS_SCHE_W, 5000, cid);
    }


    @GetMapping(BANNERS)
    public Object banners(@RequestParam(defaultValue = "") String cid) {
        return infoHandler.getDocs(BidIndex.CREATIVES_W, 500, cid);
    }

    @GetMapping(NATIVE)
    public Object natives(@RequestParam(defaultValue = "") String cid) {
        return infoHandler.getDocs(BidIndex.CREATIVES_NATIVE_W, 5000, cid);
    }

    @GetMapping("georeqs")
    public Object georeq() {
        return SimpleBidData.COUNTRY_REQUEST;
    }

    @GetMapping("appreqs")
    public Object gappreqs() {
        return SimpleBidData.APP_REQUEST;
    }

    @GetMapping("rtbcampaign/{cid}")
    public Object getCampaingsInfo(@PathVariable String cid) {
        return infoHandler.getCampaing(cid);
    }


    @GetMapping("debuglog/{on}")
    public void ping(
            @PathVariable Integer on,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if (on != null && on == 999) {
            RtbStatus.DEBUG_LOG.set(true);
        } else {
            RtbStatus.DEBUG_LOG.set(false);
        }
        String r = "" + on + RtbStatus.DEBUG_LOG.get();
        response.getOutputStream().write(r.getBytes());
        response.getOutputStream().flush();

    }


    @GetMapping("bidweight/{value}")
    public Object bidweight(
            @PathVariable Integer value,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if (value != null) {
            if (value > 100) {
                RtbStatus.RELEASE_LOCK.set(true);
                return value;
            } else {
                BidHandler.BID_WEIGHT = value;
                RtbStatus.RELEASE_LOCK.set(false);
                return "lock";
            }
        }
        return "errror value";


    }

    @Autowired
    WebApplicationContext applicationContext;

    @RequestMapping("/apis")
    public Object getAllUrl() {
        // 获取springmvc处理器映射器组件对象 RequestMappingHandlerMapping无法直接注入
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> mapone = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            // 获取url
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                mapone.put("url", url);
            }
            // 反射获取url对应类名和方法名
            mapone.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
            mapone.put("method", method.getMethod().getName()); // 方法名
            // 获取请求类型
            RequestMethodsRequestCondition methodsRequestCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsRequestCondition.getMethods()) {
                mapone.put("type", requestMethod.toString());
            }
            if (method.getMethod().getDeclaringClass().getName().indexOf("OpenApi") > 0) {
                list.add(mapone);
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        list.forEach(n -> {

            stringBuilder.append("<a target='_blank' href=\"http://rtba.mobicoca.com/" + n.get("url") + "\">" + n.get("url") + "</a><br>\n");

        });

        String s = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>Open API</title>\n" +
                "</head>\n" +
                "<body>\n" +
                stringBuilder.toString() +
                "</body>\n" +
                "</html>";

        return s;
    }


}
